package com.csjbot.blackgaga.feature.navigation;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.robot.thirdparty.google.reflect.TypeToken;
import com.bumptech.glide.Glide;
import com.csjbot.blackgaga.R;
import com.csjbot.blackgaga.base.BaseFullScreenActivity;
import com.csjbot.blackgaga.base.BasePresenter;
import com.csjbot.blackgaga.core.RobotManager;
import com.csjbot.blackgaga.global.Constants;
import com.csjbot.blackgaga.localbean.NaviBean;
import com.csjbot.blackgaga.model.tcp.bean.Position;
import com.csjbot.blackgaga.model.tcp.factory.ServerFactory;
import com.csjbot.blackgaga.router.BRouterKey;
import com.csjbot.blackgaga.router.BRouterPath;
import com.csjbot.blackgaga.util.BlackgagaLogger;
import com.csjbot.blackgaga.util.GsonUtils;
import com.csjbot.blackgaga.util.SharedKey;
import com.csjbot.blackgaga.util.SharedPreUtil;
import com.csjbot.blackgaga.widget.KeyPointView;
import com.csjbot.coshandler.core.Robot;
import com.csjbot.coshandler.listener.OnPositionListener;
import com.csjbot.coshandler.listener.OnSpeakListener;
import com.csjbot.coshandler.log.Csjlogger;
import com.iflytek.cloud.SpeechError;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xiasuhuei321 on 2017/12/20.
 * author:luo
 * e-mail:xiasuhuei321@163.com
 */

@Route(path = BRouterPath.NAVI_MAIN_NEW)
public class NaviActivityNew extends BaseFullScreenActivity {
    @BindView(R.id.rl_cancel)
    RelativeLayout rl_cancel;
    @BindView(R.id.rl_start)
    RelativeLayout rl_start;
    @BindView(R.id.iv_btn)
    ImageView iv_btn;
    @BindView(R.id.tv_goImm)
    TextView tv_goImm;
    @BindView(R.id.iv_map)
    ImageView iv_map;
    @BindView(R.id.rl_map)
    RelativeLayout rl_map;
    @BindView(R.id.rl_info)
    RelativeLayout rl_info;
    @BindView(R.id.tv_hint)
    TextView tv_hint;
    @BindView(R.id.tv_navi_name)
    TextView tv_navi_name;
    @BindView(R.id.tv_desc)
    TextView tv_desc;

    // 如果为 true 说明是说了一个没有的点
    @Autowired(name = BRouterKey.NO_POINT_GUIDE)
    boolean isFromAI = false;

    public static final int GUIDE_ALL = 10086;
    public static final int GUIDE_SINGLE = 10087;
    public static final int GUIDE_BACK = 10088;
    public static final int GUIDE_DEFAULT = -1;
    public volatile int workType = GUIDE_DEFAULT;
    private volatile Runnable currentRunnable;
    private int nodeCount = 0;
    private int guideClickCount = 0;

    // 导航点数据
    public List<NaviBean> naviBeanList = null;
    // 这个集合保存的是需要导航的店的信息
    public List<NaviBean> workList = new ArrayList<>();

    public TaskStatusManager guideSingle;
    private ArmLooper armLooper = new ArmLooper();

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_navi_new;
    }

    @Override
    public void afterViewCreated(Bundle savedInstanceState) {
        guideSingle = new TaskStatusManager();
        IntentFilter filter = new IntentFilter(Constants.WAKE_UP);
        registerReceiver(receiver, filter);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (workType == GUIDE_SINGLE) {
                if (guideSingle.workStatus == TaskStatusManager.START) {
                    guideImm();
                }
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        // 刷新一下全局导航的数据
        NaviAction.getInstance().initData();

        RobotManager.getInstance().addListener(positionListener);
        if (!Constants.isLoadMapSuccess) {
            Toast.makeText(this, R.string.plz_restore_map_tip, Toast.LENGTH_LONG).show();
        }
        String json = SharedPreUtil.getString(SharedKey.NAVI_NAME, SharedKey.NAVI_KEY);
        if (TextUtils.isEmpty(json)) {
            // 获取的 json 为空
            String mapPath = SharedPreUtil.getString(SharedKey.NAVI_NAME, SharedKey.MAP_PATH);
            // 获取不到地图，提示用户添加地图
            if (TextUtils.isEmpty(mapPath)) {
                BlackgagaLogger.debug("Navi:没有地图");
            } else {
                // 有地图，但是没设置
                BlackgagaLogger.debug("Navi:地图路径：" + mapPath);
                Glide.with(this).load(mapPath).into(iv_map);
            }
        } else {
            BlackgagaLogger.debug("Navi:导航地图数据\n" + json);

            String mapPath = SharedPreUtil.getString(SharedKey.NAVI_NAME, SharedKey.MAP_PATH);
            naviBeanList = GsonUtils.jsonToObject(json, new TypeToken<List<NaviBean>>() {
            }.getType());

            if (!TextUtils.isEmpty(mapPath)) {
                BlackgagaLogger.debug("Navi:地图路径：" + mapPath);
                Glide.with(this).load(mapPath).into(iv_map);
            }

            if (naviBeanList == null || naviBeanList.size() <= 0) {
                BlackgagaLogger.debug("Navi:没有数据");
            } else {
                BlackgagaLogger.debug("Navi:获取到关键点数量：" + naviBeanList.size());
                initMap(naviBeanList);
            }
        }
    }

    /**
     * 初始化地图，将点绘制到地图上
     */
    private void initMap(List<NaviBean> naviList) {
        int count = rl_map.getChildCount() - 1;
        if (count >= 2) {
            while (count > 1) {
                rl_map.removeViewAt(count);
                count--;
            }
        }

        for (NaviBean n : naviList) {
            addPointView(n);
        }
    }

    /**
     * 在有数据的情况下添加导引点到地图上
     */
    private void addPointView(NaviBean naviBean) {
        KeyPointView keyPointView = new KeyPointView(this);

        keyPointView.setName(naviBean.getName());
        keyPointView.layout(naviBean.left, naviBean.top, naviBean.right, naviBean.bottom);
        keyPointView.setTranslationX(naviBean.getTranslationX());
        keyPointView.setTranslationY(naviBean.getTranslationY());

        BlackgagaLogger.debug("Navi:left=" + naviBean.left + " top=" + naviBean.top + " right=" + naviBean.right + " bottom=" + naviBean.bottom);

        keyPointView.setName(naviBean.getName());
        keyPointView.setOnClickListener(v -> {
            showInfo(naviBean);
        });

        rl_map.addView(keyPointView);
    }

    private NaviBean currentSelect = null;
    public static final String START_HINT = "请在地图左侧选择你要去的地点，点击地图标注即可";
    public static final String BACK_HINT = "正在返回迎宾点，请稍后...";

    /**
     * 当用户点击后，展示地图信息
     */
    public void showInfo(NaviBean n) {
        currentSelect = n;
        tv_hint.setVisibility(View.GONE);
        rl_info.setVisibility(View.VISIBLE);

        tv_navi_name.setText(n.getName());
        tv_desc.setText(n.getDescription());
    }

    public void hideInfo(String text) {
        rl_info.setVisibility(View.GONE);
        tv_hint.setVisibility(View.VISIBLE);

        tv_hint.setText(text);
    }

    @OnClick(R.id.rl_start)
    public void guideImm() {
        if (workType == GUIDE_BACK) {
            speak(R.string.working_ing, true);
            BlackgagaLogger.debug("Navi:正在执行返回动作，单步导览无法进行");
            return;
        }

        workType = GUIDE_SINGLE;

        switch (guideSingle.workStatus) {
            case TaskStatusManager.AWAIT:
                guideSingle.start();
                startGuideSingle();
                break;

            case TaskStatusManager.PAUSE:
                guideSingle.resume();
                resumeGuideSingle();
                break;

            case TaskStatusManager.START:
                guideSingle.pause();
                pauseGuideSingle();
                break;
        }
    }

    private void pauseGuideSingle() {
        cancelTask();
    }

    private void resumeGuideSingle() {
        startGuideSingle();
    }

    private void startGuideSingle() {
        if (currentSelect == null) {
            speak(getString(R.string.no_select_point), true);
        } else {
            speak(R.string.go_with_me, true);
            startGuideSingleCount();
            startingGuideSingle();
            RobotManager.getInstance().robot.reqProxy.navi(currentSelect.toJson());
        }
    }


    @OnClick(R.id.rl_cancel)
    public void cancel() {
        rl_start.setEnabled(true);
        backWelCome();
    }

    public void backWelCome() {
        String json = SharedPreUtil.getString(SharedKey.YINGBIN_NAME, SharedKey.YINGBIN_KEY);
        List<Position> positionList = GsonUtils.jsonToObject(json, new TypeToken<List<Position>>() {
        }.getType());

        if (positionList == null || positionList.size() <= 0) {
            Toast.makeText(context, R.string.no_yinbin, Toast.LENGTH_SHORT).show();
            BlackgagaLogger.debug("Navi:尚未设置迎宾点");
            return;
        }

        if (workType == GUIDE_BACK) {
            return;
        }
        stopSpeak();
        cancelTask();
        if (currentRunnable != null) {
            handler.removeCallbacks(currentRunnable);
        }

        workType = GUIDE_BACK;
        Position position = positionList.get(0);
        handler.postDelayed(() -> {
            RobotManager.getInstance().robot.reqProxy.navi(position.toJson());
            BlackgagaLogger.debug(json);
        }, 1000);
    }

    /**
     * 单项导览移动结果回调
     */
    public void guideSingleMoveResult(NaviBean naviBean, boolean isSuccess) {
        // 已经结束了
        BlackgagaLogger.debug("Navi:单项导航");
        hideInfo(BACK_HINT);
        rl_start.setEnabled(false);
        speak(naviBean.getName() + getString(R.string.arrived), new OnSpeakListener() {
            @Override
            public void onSpeakBegin() {

            }

            @Override
            public void onCompleted(SpeechError speechError) {
                handler.postDelayed(() -> speak(naviBean.getDescription(), new OnSpeakListener() {
                    @Override
                    public void onSpeakBegin() {

                    }

                    @Override
                    public void onCompleted(SpeechError speechError) {
                        handler.postDelayed(NaviActivityNew.this::backWelCome, 2000);
                        rl_start.setEnabled(true);
                    }
                }, true), 1000);
            }
        });

        if (!isFromAI) backWelCome();
        else {
            speak(currentSelect.getName() + getString(R.string.arrived) + getString(R.string.back_help_find));
            // TODO: 2017/12/12 跳转到评价界面
        }
    }

    /**
     * 分发移动结果
     */
    OnPositionListener positionListener = new OnPositionListener() {
        @Override
        public void positionInfo(String json) {

        }

        @Override
        public void moveResult(String json) {
            runOnUiThread(() -> {
                BlackgagaLogger.debug("进入了移动结果回调，返回json：" + json);
                int error_code = 0;
                try {
                    JSONObject jsonObj = new JSONObject(json);
                    error_code = jsonObj.optInt("error_code");

                } catch (Exception e) {
                    Csjlogger.error(e);
                    e.printStackTrace();
                }
                if (workType == GUIDE_SINGLE) {
                    if (error_code == 0) {
                        armLooper.stopLooper();
                        guideSingleMoveResult(currentSelect, true);
                    }
                }
            });
        }

        @Override
        public void moveToResult(String json) {
            BlackgagaLogger.debug("消息下发成功");
            runOnUiThread(() -> {
                if (workType == GUIDE_SINGLE) {
                    isGuideSinglePush = true;
                    cancelGuideSingle();
                    armLooper.startLooper();
                    ServerFactory.getActionInstance().nodAction();
                } else if (workType == GUIDE_BACK) {
                    armLooper.startLooper();
                    initGuideSingle(BACK_HINT);
                }
            });
        }

        @Override
        public void cancelResult(String json) {
//            try {
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
        }
    };


    boolean cancelFlag = false;
    boolean inRunning = false;

    /**
     * 取消任务
     */
    public void cancelTask() {
        handler.sendEmptyMessageDelayed(CANCEL_TASK, 5000);
        RobotManager.getInstance().robot.reqProxy.cancelNavi();
        inRunning = false;
        cancelFlag = true;
    }

    private static final int CANCEL_TASK = 11111111;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CANCEL_TASK:
                    BlackgagaLogger.debug("消息还是发到这了？");
                    if (workType == GUIDE_BACK) {
                    }

                    if (workType == GUIDE_SINGLE) {
                    }

                    break;
                default:

                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        Robot.getInstance().setPositionListener(null);
        cancelTask();
        handler.removeCallbacksAndMessages(null);
        handler.removeMessages(CANCEL_TASK);
        armLooper.stopLooper();
    }

    public void backYinbin() {
        String j = SharedPreUtil.getString(SharedKey.YINGBIN_NAME, SharedKey.YINGBIN_KEY);
        List<Position> positionList = GsonUtils.jsonToObject(j, new TypeToken<List<Position>>() {
        }.getType());

        RobotManager.getInstance().robot.reqProxy.navi(positionList.get(0).toJson());
        BlackgagaLogger.debug(j);
    }

    /**
     * 切换到单步导览启动中状态
     */
    public void startingGuideSingle() {
        tv_goImm.setText(R.string.starting_single);
        rl_start.setEnabled(false);
    }

    /**
     * 切换到奥单步导览运行中状态
     */
    public void inRunningGuideSingle() {
        rl_start.setEnabled(true);
        guideSingle.start();
        tv_goImm.setText(R.string.pause);
    }

    CountDownTimer guideSingleTimer;
    volatile boolean isGuideSinglePush = false;

    private void startGuideSingleCount() {

        guideSingleTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                if (!isGuideSinglePush) {
                    BlackgagaLogger.debug("Navi:单项导览消息下发超时");
                    Toast.makeText(context, R.string.start_failed_check, Toast.LENGTH_SHORT).show();
                    initGuideSingle();
                    // 重置标识
                    guideSingle.workStatus = TaskStatusManager.AWAIT;
                    workType = GUIDE_DEFAULT;
                }
            }
        };

        guideSingleTimer.start();
    }

    private void initGuideSingle() {
        initGuideSingle(START_HINT);
    }

    private void initGuideSingle(String text) {
        tv_goImm.setText(R.string.go_imm);
        hideInfo(text);
        rl_start.setEnabled(true);
    }

    private void cancelGuideSingle() {
        if (guideSingleTimer != null) {
            guideSingleTimer.cancel();
        }
        inRunningGuideSingle();
    }
}
